package com.jiuyin.dianjing.ui.fragment.match;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.adapter.BaseRecyclerAdapter;
import com.jiuyin.dianjing.adapter.SmartViewHolder;
import com.jiuyin.dianjing.api.enums.ApiEnum;
import com.jiuyin.dianjing.api.interfaces.ApiResultCallback;
import com.jiuyin.dianjing.api.interfaces.ProgressDialogCallback;
import com.jiuyin.dianjing.api.server.ServerApi;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.model.CompeteDetail;
import com.jiuyin.dianjing.model.MatchResultModel;
import com.jiuyin.dianjing.ui.fragment.base.BaseLazyFragment;
import com.jiuyin.dianjing.util.LogUtil;
import com.jiuyin.dianjing.util.ToastUtil;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_COMPETITIONID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_COMPETITION_ID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TACTICS;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOKEN;

/**
 * 比赛排名
 */
public class FragmentMatchRanking extends BaseLazyFragment {
    @BindView(R.id.lv_match_results)
    RecyclerView mRvMatchResults;
    @BindView(R.id.tv_match_competitor_key)
    TextView mTvTitle;
    @BindView(R.id.tv_has_ended)
    Button btEnded;
    @BindView(R.id.empty)
    View mEmptyLayout;
    @BindView(R.id.empty_text)
    TextView mEmptyText;
    @BindView(R.id.empty_image)
    ImageView mEmptyImage;

    private BaseRecyclerAdapter<MatchResultModel> mAdapter;
    private static final String KEY = "KEY";

    public static FragmentMatchRanking newInstance(String competitionId) {
        Bundle bundle = new Bundle();
        bundle.putString(KEY, competitionId);
        FragmentMatchRanking fragmentGame = new FragmentMatchRanking();
        fragmentGame.setArguments(bundle);
        return fragmentGame;
    }

    @Override
    public void fetchData() {
        String competitionId = getArguments().getString(KEY);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put(KEY_TOKEN, HelperApplication.getToken());
        hashMap.put(KEY_COMPETITIONID, competitionId);
        JSONObject data = new JSONObject(hashMap);
        ApiResultCallback request = new ApiResultCallback() {
            @Override
            public void onSuccess(JsonObject data) {
                CompeteDetail compete = new Gson().fromJson(data, CompeteDetail.class);
                int tactics = compete.tactics;
                String competition_id = compete.course.competition_id;
                getMatchRanking(tactics, competition_id);
                switch (compete.course.competeCourse) {
                    case 0:
                        btEnded.setText(R.string.match_registration_not_started);
                        break;
                    case 1:
                        btEnded.setText(R.string.match_registration_sign_up);
                        break;
                    case 2:
                        btEnded.setText(R.string.match_registration_end);
                        break;
                    case 3:
                        btEnded.setText(R.string.match_registration_game_begun);
                        break;
                    case 4:
                        btEnded.setText(R.string.match_match_end);
                        break;
                }
            }

            @Override
            public void onFail(String msg) {
                ToastUtil.showShort(msg);
                showEmpty();
            }

            @Override
            public void onError(String msg) {
                showEmpty();
                LogUtil.log(msg);
            }
        };
        ProgressDialogCallback defaultProgressDialogCallback = new ProgressDialogCallback() {
            @Override
            public void showProgressDialog() {
                showLoading();
            }

            @Override
            public void dismissProgressDialog() {
                dismissLoading();
            }
        };
        ServerApi.post(ApiEnum.APP_COMPETE_DETAIL_API.getUrl(), data, null, defaultProgressDialogCallback, d -> addDisposable(d), request);
    }

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_match_ranking;
    }

    @Override
    protected void initData() {
        mAdapter = new BaseRecyclerAdapter<MatchResultModel>(R.layout.item_match_result) {
            @Override
            protected void onBindViewHolder(SmartViewHolder holder, MatchResultModel model, int position) {
                if (null != model) {
                    holder.text(R.id.tv_match_title, model.name);
                    TextView tvRank = holder.itemView.findViewById(R.id.tv_match_ranking);
                    ImageView ivHead = holder.itemView.findViewById(R.id.img_head);
                    ImageView ivmedal = holder.itemView.findViewById(R.id.iv_match_medal);
                    LinearLayout llRank = holder.itemView.findViewById(R.id.ll_match_ranking);
                    if (model.ranking.equals("1")) {
                        tvRank.setText("冠军");
                        ivmedal.setImageDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.guanjun));
                    } else if (model.ranking.equals("2")) {
                        tvRank.setText("亚军");
                        ivmedal.setImageDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.yajun));
                    } else if (model.ranking.equals("3")) {
                        tvRank.setText("季军");
                        ivmedal.setImageDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.jijun));
                    } else {
                        llRank.setVisibility(View.GONE);
                    }
                    Glide.with(getActivity())
                            .load(model.logo)
                            .override(ivHead.getWidth(), ivHead.getHeight())
                            .into(ivHead);
                }
            }
        };
        mRvMatchResults.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));
        mRvMatchResults.setItemAnimator(new DefaultItemAnimator());
        mRvMatchResults.setAdapter(mAdapter);
    }

    @Override
    protected void initView() {
        mEmptyText.setText(R.string.data_null);
        mEmptyImage.setImageResource(R.drawable.ic_empty);
    }

    private void getMatchRanking(final int tactics, final String competition_id) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put(KEY_TOKEN, HelperApplication.getToken());
        hashMap.put(KEY_COMPETITION_ID, competition_id);
        hashMap.put(KEY_TACTICS, tactics);
        JSONObject data = new JSONObject(hashMap);
        ApiResultCallback request = new ApiResultCallback() {
            @Override
            public void onSuccess(JsonObject data) {
                List<MatchResultModel> list = new Gson().fromJson(data.get("rankingList"), new TypeToken<List<MatchResultModel>>() {
                }.getType());
                if (null != list && 0 != list.size()) {
                    onRefresh(list);
                } else {
                    showEmpty();
                }
            }

            @Override
            public void onFail(String msg) {
                showEmpty();
            }

            @Override
            public void onError(String msg) {
                showEmpty();
            }
        };
        ProgressDialogCallback defaultProgressDialogCallback = new ProgressDialogCallback() {
            @Override
            public void showProgressDialog() {
                showLoading();
            }

            @Override
            public void dismissProgressDialog() {
                dismissLoading();
            }
        };
        ServerApi.post(ApiEnum.APP_GET_COMPETE_RANKING_LIST.getUrl(), data, null, defaultProgressDialogCallback, d -> addDisposable(d), request);
    }

    private void onRefresh(List<MatchResultModel> models) {
        btEnded.setVisibility(View.VISIBLE);
        mTvTitle.setVisibility(View.VISIBLE);
        mAdapter.refresh(models);
    }

    /**
     * 显示空
     */
    private void showEmpty() {
        if (0 == mAdapter.getItemCount()) {
            if (View.VISIBLE != mEmptyLayout.getVisibility()) {
                mEmptyLayout.setVisibility(View.VISIBLE);
            }
        }
    }
}
